package com.huhu.weixin.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.huhu.weixin.common.Configure;
import com.huhu.weixin.common.WechatNotify;
import com.huhu.weixin.common.WechatUtil;
import com.huhu.weixin.service.WechatPayService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@RequestMapping("wxpay")
@Controller
public class WechatPayController {

    @Autowired
    private WechatPayService payService;

    @RequestMapping("payment.htm")
    public String payment(@RequestParam(required = false) String code, Model model, HttpServletRequest request){
        String openId = payService.takeOpenId(code);
        if (StringUtils.isEmpty(openId)) {
            return "pay/wxpay_error";
        }
        String notify = "http://www.xxxxxx.net/wxpay/notify.htm";
        String body = "商品支付内容";
        String total = "1"; // 单位分
        String out_trade_no = new Date().getTime() + "";

        String res = payService.unifiedorder(notify, openId, body, total, out_trade_no);

        String url = "http://www.xxxxxx.net/wxpay/payment.htm";
        payService.wechatPay(model,res,url);
        return "pay/wxpay";
    }

    /**
     * 微信支付成功后的回调函数
     *
     * @param request
     * @return
     */
    @RequestMapping(value="notify.htm",method=RequestMethod.POST)
    @ResponseBody
    public String wechatNotify(HttpServletRequest request){
        // 从 request 对象中获取 WechatNotify 对象
        WechatNotify notify = WechatUtil.getNotifyBean(request);
        // 如果 notify 对象不为空 并且 result_code 和 return_code 都为 'SUCCESS' 则表示支付成功
        if (notify != null
                && StringUtils.equals(notify.getResult_code(), Configure.SUCCESS)
                && StringUtils.equals(notify.getReturn_code(), Configure.SUCCESS)) {

            return Configure.NOTIFY_SUCCESS;
        }
        return Configure.NOTIFY_FAIL;
    }
}
